﻿import QtQuick 2.15
import QtQuick.Controls 2.15

Item {
    width: 400
    height: 40

    // 暴露的日期属性
    property date startDate: new Date(2025, 0, 16)
    property date endDate: new Date(2025, 0, 23)

    Row {
        spacing: 8
        anchors.centerIn: parent

        // 开始日期框
        Rectangle {
            width: 150
            height: 40
            color: "#1E1E1E"
            radius: 4

            Text {
                text: Qt.formatDate(startDate, "yyyy-MM-dd")
                color: "white"
                anchors.centerIn: parent
            }

            MouseArea {
                anchors.fill: parent
                onClicked: calendar.show(startDate, function(date){ startDate = date })
            }
        }

        // 波浪分隔符
        Text {
            text: "~"
            color: "white"
            font.pixelSize: 24
            anchors.verticalCenter: parent.verticalCenter
        }

        // 结束日期框
        Rectangle {
            width: 150
            height: 40
            color: "#1E1E1E"
            radius: 4

            Text {
                text: Qt.formatDate(endDate, "yyyy-MM-dd")
                color: "white"
                anchors.centerIn: parent
            }

            MouseArea {
                anchors.fill: parent
                onClicked: calendar.show(endDate, function(date){ endDate = date })
            }
        }
    }

    // 共享日历组件
    Popup {
        id: calendar
        width: 300
        height: 300

        function show(initialDate, callback) {
            calendarLoader.active = true
            calendarLoader.item.dateSelected.connect(callback)
            calendarLoader.item.selectedDate = initialDate
            x = parent.mapToItem(null, mouseX - width/2, 40).x
            open()
        }

        Loader {
            id: calendarLoader
            active: false
            sourceComponent: Calendar {
                onSelectedDateChanged: {
                    dateSelected(selectedDate)
                    calendar.close()
                }
                signal dateSelected(date selectedDate)
            }
        }
    }
}